<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;

class BaseController extends Controller
{

    /**
     * 创建成功
     * @param array $data
     * @param string $message
     * @return mixed ->setStatusCode($responseCode);  $this->statusCode < 100 || $this->statusCode >= 600 ->header('Content-Type',$contentType);
     */
    public function success($data = [],$message='')
    {

        $status = 200;
        if (!$message) {
            $message = '成功';
        }
        $result = [
          'status' => $status,
          'message' => $message,
          'data' => $data
        ];
        $http_status = 200;
        return response()->json($result)->setStatusCode($http_status);
    }

    /**
     * 业务异常
     * @param array $codeResponse
     * @param string $error
     * @return JsonResponse|object
     */
    public function fail(array $codeResponse,string $error='')
    {
        list($status,$message) = $codeResponse;
        $result = [
            'status' => $status,
            'message' => $error ? $error:$message
        ];
        $http_status = 422;
        return response()->json($result)->setStatusCode($http_status);
    }

    /**
     * 分页输出
     * @param $page
     * @return array
     */
    public function successPagniate($page)
    {
        if ($page instanceof LengthAwarePaginator) {
            $total = $page->total();
            return [
                'total' => $page->total(),
                'page' => $total == 0 ? 0 : $page->currentPage(),
                'limit' => $page->perPage(),
                'pages' => $total == 0 ? 0 : $page->lastPage(),
                'list' => $list ?? $page->items()
            ];
        }
    }
}
